package com.itheima.tanhua.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.itheima.autoconfig.template.AipFaceTemplate;
import com.itheima.autoconfig.template.OssTemplate;
import com.itheima.tanhua.api.db.UserInfoServiceApi;
import com.itheima.tanhuan.dto.db.UserInfoDto;
import com.itheima.tanhuan.pojo.db.UserInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {


    @Autowired
    private UserService userService;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @DubboReference
    private UserInfoServiceApi userInfoServiceApi;

    /**
     * 完善个人信息
     * @param token
     * @param userInfoDto
     */
    public void loginReginfo(String token, UserInfoDto userInfoDto) {
        //1、token校验
        //2、获取登陆者用户id
        Long id = userService.getUserToken(token);
        //3、组装userInfo对象信息
        UserInfo userInfo=new UserInfo();
        //利用cope工具进行对象属性值得赋值
        BeanUtil.copyProperties(userInfoDto,userInfo);
        //补充用户详细信息id为当前登录者id
        userInfo.setId(Convert.toLong(id));
        //执行新增
        userInfoServiceApi.saveUserInfo(userInfo);
    }

    /**
     * 头像上传
     * @param token
     * @param headPhoto
     */
    public Integer uploadHead(String token, MultipartFile headPhoto) {
        Long uid = userService.getUserToken(token);

        Integer flag=0;

        try{
            //2、调用上传功能
            String imagePath = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

            //人脸识别：监测当前头像是否是人像，如果不是人像，之前报错，不进行头像存储
            //Integer code = FaceUtil.checkFace(imagePath);
            boolean detect = aipFaceTemplate.detect(imagePath);

            if (!detect){
                //throw new ConsumertException("上传头像非人像！");
                //flag=1;
                return 1;
            }


            //3、创建UserInfo对象
            UserInfo userInfo=new UserInfo();
            userInfo.setId(uid);
            userInfo.setAvatar(imagePath);
            //4、更新用户信息（更新用户信息中的头像）
            userInfoServiceApi.updateAvatar(userInfo);
        }catch (IOException e){
            flag=2;
            //throw new ConsumertException("头像上传失败！");
        }

        return flag;
    }


}
